<template>
  <div class="app-container">
    <!--搜索面板-->
    <div class="filter-container">
      <el-form :model="searchForm" status-icon ref="searchForm" label-width="80px">
        <el-row>
          <el-col :sm='6'>
            <el-form-item label="用户账号" prop="username">
              <el-input v-model.trim="searchForm.username" placeholder="请输入用户账号" clearable
                        @keyup.enter.native="handleFilter"/>
            </el-form-item>
          </el-col>
          <el-col :sm='6'>
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="searchForm.name" placeholder="请输入名称" clearable
                        @keyup.enter.native="handleFilter"/>
            </el-form-item>
          </el-col>
            <el-col :sm='6'>
                <el-form-item label="类型" prop="name">
                    <el-select v-model.trim="searchForm.type" placeholder="请输入类型" clearable
                    @keyup.enter.native="handleFilter">
                        <el-option value="SYSTEM" label="系统用户"/>
                        <el-option value="AGENT" label="代理商"/>

                    </el-select>
                </el-form-item>
            </el-col>
          <el-col :sm="12">
            <el-form-item label-width="20px">
              <el-button v-waves type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
              <el-button v-waves type="default" icon="el-icon-refresh" @click="handleReset">重置</el-button>
              <el-button v-waves type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
              <el-button v-waves type="danger" icon="el-icon-delete" @click="handleDelete()">批量删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--搜索面板-->
    <div class="containtable">
      <PageTable class="containtable" :query-method="userPage" :query-form="searchForm" ref="pageTable">
        <el-table-column label="用户账号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">可用</span>
            <span v-else>不可用</span>
          </template>
        </el-table-column>
          <el-table-column label="类型" align="center">
              <template slot-scope="scope">
                  <span>{{ scope.row.typeName }}</span>
              </template>
          </el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-remove" @click="handleDelete(scope.row.id)">删除
            </el-button>
            <el-button type="warning" style='width: auto;' size="mini" icon="el-icon-magic-stick"
                       @click="handleResetPwd(scope.row.id)">重置密码
            </el-button>
          </template>
        </el-table-column>
      </PageTable>
      <!--表格-->
    </div>

    <!--新增-->
    <el-dialog title="添加用户" :visible.sync="editForm.show" :center="true" width="880px">
      <el-form status-icon :rules="editForm.rules" :model="editForm" ref="editForm" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户账号" prop="username">
              <el-input type="text" v-model="editForm.username" placeholder="请输入用户账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input type="text" v-model="editForm.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="showPwd">
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="editForm.password" placeholder="请输入密码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="password2">
              <el-input type="password" v-model="editForm.password2" placeholder="请输入密码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="电话" prop="phone">
              <el-input type="text" v-model="editForm.phone" :maxlength="11" placeholder="请输入电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色" prop="roles">
              <el-select v-model="editForm.roles.value" multiple placeholder="请选择">
                <el-option v-for="item in editForm.roles.item" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态" prop="radio">
              <el-radio-group v-model="editForm.radio">
                <el-radio :label="0">可用</el-radio>
                <el-radio :label="1">不可用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
              <el-col :span="24">
                  <el-form-item label="类型" prop="radio">
                      <el-radio-group v-model="editForm.type">
                          <el-radio label="SYSTEM">系统用户</el-radio>
                          <el-radio label="AGENT">代理商</el-radio>
                      </el-radio-group>
                  </el-form-item>
              </el-col>
          </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-waves @click="onSubmit('editForm')" icon="el-icon-success">提交</el-button>
        <el-button class="cancel-btn" v-waves @click="cancelsub" icon="el-icon-error">取消</el-button>
      </div>
    </el-dialog>
    <!--新增-->
  </div>
</template>
<script>
import waves from '@/directive/waves' // Waves directive
import PageTable from "@/components/Pagination/PageTable";
import {
  userPage,
  rolePage,
  checkUserName,
  userDetail,
  userEdit,
  userDel,
  userReset
} from '@/api/admin/system/user' //调用模块接口
export default {
  name: 'userManage',
  components: {
    PageTable
  },
  directives: {
    waves
  },
  data() {
    var checkPass = (rule, value, callback) => {
      if (this.editForm.id == '') {
        if (this.editForm.password == '') {
          return callback(new Error('请输入密码'));
        }
      }
      if (this.editForm.password !== this.editForm.password2) {
        return callback(new Error('两次输入的密码不相同'));
      } else {
        callback();
      }
    };
    var checkPassword = ((rule, value, callback) => {
      if (this.editForm.id == '') {
        if (this.editForm.password == '') {
          checkPass(rule, value, callback);
          return callback(new Error('请输入密码'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    });
    var checkUser = (rule, value, callback) => {
      if (this.editForm.username == this.editForm.nowusername && this.editForm.username != '') {
        callback();
      }
      this.checkUserNames(rule, value, callback);
    };
    var checkRole = (rule, value, callback) => {
      if (this.editForm.roles.value == 0) {
        return callback(new Error('请选择角色'));
      } else {
        callback();
      }
    };
    return {
      userPage,
      tabPosition: 'left',//标签方向的设置
      searchForm: {
        username: '',
        name: ''
      },
      showPwd: true,
      editForm: {
        show: false,
        username: '',
        nowusername: '',
        name: '',
        id: '',
        phone: '',
        radio: 1,
        password: '',
        password2: '',
          type:"",
        roles: {
          item: [],
          value: []
        },
        rules: {
          password: [{
            validator: checkPassword,
            trigger: 'blur'
          }],
          password2: [{
            validator: checkPass,
            trigger: 'blur'
          }],
          username: [{
            validator: checkUser,
            required: true,
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          roles: [{
            validator: checkRole,
            required: true,
            trigger: 'blur'
          }]
        }
      },
      tableData: {
        emptyText: '暂无数据',
        listLoading: false,
        list: [],
        total: 0,
        listQuery: {
          pageNumber: 1,
          pageSize: 10
        }
      }
    }
  },
  methods: {
    handleFilter() {
      this.$refs.pageTable.reset();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.$refs.pageTable.reset();
    },
    handleAdd() {
      this.showPwd = true;
      this.editForm.id = '';
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        this.$refs.editForm.resetFields();
      });
      this.editForm.show = true;
      this.editForm.roles.value = [];
    },
    handleUpdate(row) {
      this.showPwd = false;
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        this.$refs.editForm.resetFields();
      });
      this.editForm.show = true;
      this.handleUserDetail(row.id);
    },
    //获取角色
    handleRolePage() {
      rolePage({
        role: '',
        name: ''
      }).then(res => {
        this.editForm.roles.item = [];
        this.editForm.roles.value = [];
        if (res.data.list) {
          this.editForm.roles.item = res.data.list.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
        }
      })
    },
    //用户详情
    handleUserDetail(id) {
      this.editForm.id = id;
      userDetail({
        id
      }).then(res => {
        this.editForm.roles.value = [];
        this.editForm.username = res.data.user.username;
        this.editForm.nowusername = res.data.user.username;
        this.editForm.name = res.data.user.name;
        this.editForm.phone = res.data.user.phone;
        this.editForm.radio = res.data.user.status;
          this.editForm.type = res.data.user.type;
        this.editForm.roles.value = res.data.userRole.map(item => {
          return item.id
        });
      })
    },
    //验证用户名是否存在
    checkUserNames(rule, value, callback) {
      if (this.editForm.username == '' || this.editForm.username == null) {
        return callback(new Error('请填写用户名'));
      }
      checkUserName({
        id: this.editForm.id,
        username: this.editForm.username
      }).then(res => {
        if (res.data.exist) {
          return callback(new Error('当前用户名已存在'));
        } else {
          callback();
        }
      })
    },
    //提交表单
    onSubmit(editForm) {
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          userEdit({
            id: this.editForm.id,
            name: this.editForm.name,
            username: this.editForm.username,
            password: this.editForm.password,
            phone: this.editForm.phone,
            status: this.editForm.radio,
              type : this.editForm.type,
            roleId: this.editForm.roles.value.join(',')
          }).then(res => {
            this.$notify({
              title: '提示',
              message: '信息提交成功',
              type: 'success'
            });
            this.$refs.pageTable.refresh();
            this.editForm.show = false;
          })
        } else {
          return false;
        }
      })
    },
    //删除用户
    handleDelete(id) {
      if (!id) {
        id = this.$refs.pageTable.selects.map(item => item.id).join(',')
      }
      if (!id) {
        this.$message({
          type: 'error',
          message: '请选择要操作的记录!'
        });
        return;
      }
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userDel({
          ids: id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.$refs.pageTable.refresh();
        })
      })
    },
    //重置密码
    handleResetPwd(id) {
      this.editForm.id = id;
      this.$confirm('是否重置密码为123456, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userReset({
          id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '成功!'
          });
          this.$refs.pageTable.refresh();
        })
      })
    },
    // 取消提交
    cancelsub: function () {
      this.editForm.show = false;
    }
  },
  mounted() {
    this.$refs.pageTable.refresh();
    this.handleRolePage();
  }
}
</script>

<style>
</style>
